/*
 * @Author: zhang00001 774004514@qq.com
 * @Date: 2024-06-14 16:17:15
 * @LastEditors: yansheng 610363806@qq.com
 * @LastEditTime: 2024-07-27 02:55:13
 * @FilePath: \vue-admin\src\utils\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// http.js
import axios from 'axios'
import { getToken, removeToken, setToken } from '@/utils/storage'
import Base64 from 'base-64';
// 环境的切换
import { message } from 'ant-design-vue'
import config from '@/config/index.js'
import router from "@/router"
// import { useRouter } from 'vue-router'

axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? '/admin' : import.meta.env.VITE_BASIC_URL
let refToken = ""
let token = getToken()
    // 请求拦截器
axios.interceptors.request.use(
    config => {

        // config.header.Authorization = `Basic ${ Base64.encode(token+':')}`
        token = getToken()

        token && (config.headers.Authorization = `Basic ${ Base64.encode(token+':')}`)

        return config
    },
    error => {
        return Promise.error(error)
    })

axios.defaults.timeout = 10000

axios.defaults.headers.post['Content-Type'] = 'application/json'

// 响应拦截器
axios.interceptors.response.use(response => {

    // const router = useRouter()
    if (response.status === 200) {
        // if (response.headers.token) {
        //     refToken = response.headers.token
        //     console.log('refToken' + response.headers.token)
        //     setToken(response.headers.token)
        // }

        if (response.data.errorCode == 10006) {
            message.error(response.data.msg)
                // 跳转登录页面
            let fullPath = `${router.currentRoute.value.path}`
                // router.push(`/login?redirect=${fullPath}`)

            window.location.href = `/#/login?redirect=${fullPath}`
                // 清除token
            removeToken()
        } else
        if (response.data.errorCode) {
            // message.error(response.data.msg)
            return Promise.resolve(response)
                // 未授权调取授权接口
        } else {
            return Promise.resolve(response)
        }
    } else {
        message.error(response.msg)
        return Promise.reject(response)
    }
}, error => {

    // 我们可以在这里对异常状态作统一处理
    if (error.response && error.response.status) {

        message.error(error.response.data.msg)
            // 处理请求失败的情况
            // 对不同返回码对相应处理
        return Promise.reject(error.response.data)
    }
})

// get 请求
export function httpGet({
    url,
    params = {}
}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params
        }).then((res) => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}

// post请求
export function httpPost({
    url,
    data = {},
    params = {}
}) {
    return new Promise((resolve, reject) => {

        axios({
            url,
            method: 'post',
            // transformRequest: [function(data) {
            //     let ret = ''
            //     for (let it in data) {
            //         ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            //     }
            //     return ret
            // }],
            // 发送的数据
            data,
            // �url参数
            params

        }).then(res => {
            resolve(res.data)
        })
    })
}
export function httpPostForm({
    url,
    data = {},
    params = {}
}) {
    return new Promise((resolve, reject) => {

        axios({
            url,
            method: 'post',
            headers: {
                Authorization: `Basic ${ Base64.encode(token+':')}`,
                'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryQ7hcnMItVOQUHpHi'
            },
            // transformRequest: [function(data) {
            //     let ret = ''
            //     for (let it in data) {
            //         ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            //     }
            //     return ret
            // }],
            // 发送的数据
            data,
            // �url参数
            params

        }).then(res => {
            resolve(res.data)
        })
    })
}
export function uploadFile(file) {

    return new Promise((resolve, reject) => {

        axios({
            method: 'post',
            url: url,
            headers: {
                Authorization: `Basic ${ Base64.encode(token+':')}`,
                'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryQ7hcnMItVOQUHpHi'
            },
            data: file,

        }).then((res) => {
            resolve(res.data);

        }).catch(err => {
            reject("Upload failed");
            console.error("Error:", err)
        })

    })
}